package com.xes.rc522_test;

import java.util.logging.LogRecord;

import android.app.Activity;
import android.nfc.cardemulation.CardEmulation;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.os.IRC522Service;

public class MainActivity extends Activity {
	private static final int RC522_BLOCK_SIZE = 16; // block data max len
	private static final int RC522_TYPE_SIZE = 2; // card type max len
	private static final int RC522_SN_SIZE = 4; // card serial number max len
	private static final int RC522_TYPESN_SIZE = RC522_TYPE_SIZE
			+ RC522_SN_SIZE; // card type + card serial number

	private TextView cardnum_text, cardb1_text, cardb2_text;
	private static final int type_num_code = 1;
	private static final int block1_data_code = 2;
	private static final int block2_data_code = 3;

	private IRC522Service rc522service = null;

	private byte[] type_num = new byte[RC522_TYPESN_SIZE];
	private byte[] block1_data = new byte[RC522_BLOCK_SIZE];
	private byte[] block2_data = new byte[RC522_BLOCK_SIZE];

	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			int code = msg.arg1;
			switch (code) {
			case type_num_code:
				cardnum_text.setText(bytesToHexString(type_num));
				break;
			case block1_data_code:
				cardb1_text.setText(bytesToHexString(block1_data));
				break;
			case block2_data_code:
				cardb2_text.setText(bytesToHexString(block2_data));
				break;
			default:
				super.handleMessage(msg);
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		cardnum_text = (TextView) findViewById(R.id.cardnum_text);
		cardb1_text = (TextView) findViewById(R.id.cardb1_text);
		cardb2_text = (TextView) findViewById(R.id.cardb2_text);

		rc522service = IRC522Service.Stub.asInterface(ServiceManager
				.getService("rc522"));

		try {
			rc522service.resetCard();
			if (rc522service.isReady()) {
				cardnum_text.setText("读卡中...");
				new Thread(new Runnable() {
					public void run() {
						int i;
						while (!Thread.currentThread().isInterrupted()) {
							try {
								if (rc522service.selectCard(type_num, 10000)) {
									Message message1 = new Message();
									message1.arg1 = type_num_code;
									handler.sendMessage(message1);
									for (i = 1; i < 3; i++) {
										Log.d("rc522", "read" + i);
										Message message2 = new Message();
										if (i == 1 && rc522service.readBlock(i, block1_data) > 0) {
											message2.arg1 = block1_data_code;
											handler.sendMessage(message2);
										} else {
											break;
										}
										if (i == 2 && rc522service.readBlock(i, block2_data) > 0) {
											message2.arg1 = block2_data_code;
											handler.sendMessage(message2);
										} else {
											break;
										}
									}
									if (i == 3) {
										rc522service.buzzer(1, 150);
									} else {
										rc522service.buzzer(3, 50);
									}
									rc522service.haltCard();
								} else {
									Log.d("rc522",
											"request card error or timeout!");
									try {
										Thread.sleep(100);
									} catch (InterruptedException e) {
										Thread.currentThread().interrupt();
									}
								}
							} catch (RemoteException e1) {
								e1.printStackTrace();
							}
						}
					}
				}).start();
			} else {
				cardnum_text.setText("未就绪");
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
